package com.jlnk.androidfmc.view;

import static com.jlnk.androidfmc.view.NewsPost.REQUEST_STORAGE_PERMISSION_CODE;
import static com.jlnk.androidfmc.view.NyqPost.PICK_IMAGE_REQUEST;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jlnk.androidfmc.R;
import com.jlnk.androidfmc.adapter.ProductAdapter;
import com.jlnk.androidfmc.database.ProductDatabaseHelper;
import com.jlnk.androidfmc.entity.Product;
import com.jlnk.androidfmc.presenter.ReleasePresenter;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ReleaseActivity extends AppCompatActivity implements ReleaseView {
    private ReleasePresenter presenter;
    private Button btnSelectImage, btnRelease;
    private ImageView imageView,backimageView;
    private EditText etTitle, etContent, etPrice;
    private Spinner spinnerCategory;
    private RecyclerView recyclerView;
    private ProductAdapter adapter;
    private List<Product> productList;
    private String imagePath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.release_activity);

        presenter = new ReleasePresenter(this);

        // 初始化UI控件
        initViews();

        // 初始化发布按钮状态
        setupReleaseButtonState();

        // 初始化RecyclerView
        initRecyclerView();

        // 初始化Spinner
        initSpinner();
    }

    private void initViews() {
        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        etPrice = findViewById(R.id.et_price);
        spinnerCategory = findViewById(R.id.spinner_category);
        imageView = findViewById(R.id.iv_image);
        btnSelectImage = findViewById(R.id.btn_select_image);
        btnRelease = findViewById(R.id.post_button);
        backimageView = findViewById(R.id.back_button);

        backimageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        setupTextWatchers();
    }

    private void setupReleaseButtonState() {
        // 初始化发布按钮为禁用状态
        btnRelease.setEnabled(false);

        // 设置发布按钮的点击事件
        btnRelease.setOnClickListener(v -> releaseProduct());

        // 设置选择图片按钮的点击事件
        btnSelectImage.setOnClickListener(v -> presenter.pickImage());
    }

    private void setupTextWatchers() {
        setupTextWatcher(etTitle);
        setupTextWatcher(etPrice);
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.rv_images);
        productList = new ArrayList<>();
        adapter = new ProductAdapter(productList);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
    }

    private void initSpinner() {
        List<String> categoriesNames = new ProductDatabaseHelper(this).getAllCategoriesNames();
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, categoriesNames);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerCategory.setAdapter(spinnerAdapter);
    }

    private void setupTextWatcher(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 根据输入情况启用或禁用发布按钮
                btnRelease.setEnabled(isFormValid());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    private boolean isFormValid() {
        // 验证名称、价格和图片是否都已填写
        String title = etTitle.getText().toString().trim();
        String priceStr = etPrice.getText().toString().trim();
        return !title.isEmpty() && isValidPrice(priceStr) && (imagePath != null && !imagePath.isEmpty());
    }

    private boolean isValidPrice(String priceStr) {
        try {
            double price = Double.parseDouble(priceStr);
            return price >= 0;
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void releaseProduct() {
        // 从UI控件获取数据
        String title = etTitle.getText().toString().trim();
        String priceStr = etPrice.getText().toString().trim();
        String content = etContent.getText().toString();
        int categoryId = getSelectedCategoryId(spinnerCategory);
        double price = (priceStr.isEmpty()) ? 0 : Double.parseDouble(priceStr);

        // 验证名称、价格和图片
        if (!isValidPrice(priceStr)) {
            Toast.makeText(this, "请输入有效的价格", Toast.LENGTH_SHORT).show();
            etPrice.requestFocus(); // 请求输入框焦点
            btnRelease.setEnabled(false); // 禁用发布按钮
            return;
        }
        if (priceStr.isEmpty()) {
            Toast.makeText(this, "价格不能为空", Toast.LENGTH_SHORT).show();
            etPrice.requestFocus(); // 请求输入框焦点
            return;
        }
        if (imagePath == null || imagePath.isEmpty()) {
            Toast.makeText(this, "请先选择图片", Toast.LENGTH_SHORT).show();
            // 可以在这里添加代码来触发图片选择，例如打开相册或相机
            return;
        }

        // 验证通过后，创建 Product 对象并发布
        Product product = new Product(null, title, content, imagePath, categoryId, price);
        presenter.releaseItem(product);
    }

    private int getSelectedCategoryId(Spinner spinner) {
        // spinner.getSelectedItemPosition() 返回的是选中项的位置，根据位置获取分类 ID
        return spinner.getSelectedItemPosition() + 1; // 通常位置是从0开始的，所以需要+1
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_STORAGE_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限授予，如果图片已经加载，现在可以保存图片
                Drawable drawable = imageView.getDrawable();
                if (imagePath == null && drawable instanceof BitmapDrawable) {
                    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                    imagePath = saveImageToExternalStorage(bitmap);
                    if (imagePath != null) {
                        btnRelease.setEnabled(true); // 启用发布按钮
                    }
                }
            } else {
                Toast.makeText(this, "Storage permission not granted", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Bitmap bitmap = null;
            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
                displayImage(bitmap);
            } catch (IOException e) {
                Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }

            if (bitmap != null && hasStoragePermission()) {
                // 如果已经有存储权限，保存图片
                imagePath = saveImageToExternalStorage(bitmap);
                if (imagePath != null) {
                    imageView.setImageURI(Uri.fromFile(new File(imagePath)));
                    btnRelease.setEnabled(true); // 用户选择了图片，启用发布按钮
                }
            } else if (bitmap != null) {
                // 如果没有存储权限，请求权限
                requestStoragePermission();
            }
        }
    }

    // 在 ReleaseActivity 中
    private String saveImageToExternalStorage(Bitmap bitmap) {
        // 确保有写外部存储的权限
        if (!hasStoragePermission()) {
            requestStoragePermission();
            return null;
        }

        // 保存图片到应用专属的外部存储目录
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        File storageDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "YourAppDir");
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
        File image = new File(storageDir, System.currentTimeMillis() + ".jpg");
        try (FileOutputStream fos = new FileOutputStream(image)) {
            fos.write(bytes.toByteArray());
            return image.getAbsolutePath();
        } catch (IOException e) {
            Toast.makeText(this, "Failed to save image", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Context getContext() {
        return this; // 返回当前 Activity 的上下文
    }
    // 实现 ReleaseView 接口的方法
    @Override
    public void showLoading() {
        // 显示加载指示器
    }

    @Override
    public void hideLoading() {
        // 隐藏加载指示器
    }

    @Override
    public void showReleaseSuccess() {
        Toast.makeText(this, "发布成功", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showReleaseError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void displayImage(Bitmap bitmap) {
        imageView.setImageBitmap(bitmap);
    }

    @Override
    public boolean hasStoragePermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void requestStoragePermission() {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_STORAGE_PERMISSION_CODE);
    }

    @Override
    public void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }
}